using System;
using Jink.Core.Converters.Annotations;
using Jink.Core.Converters.Context;
using Jink.Core.Json.Converters.Factories;
using Jink.Core.Json.Converters.Shapes.Annotations;
using Jink.Core.Json.Converters.Shapes.Core;
using Jink.Core.Json.Values;
using Jink.Playground.Domain;
using System.Linq;
using Jink.Playground.MockData;

namespace Jink.Playground
{
    [Converter]
    internal class Converters
    {
        [OnConversionContextInit]
        public static void AddSPWebOnContextInit(ConversionContext ctx)
        {
            if (ctx.Cookies.ContainsKey("jink"))
            {
                var mockWeb = new SPWeb{Lists = {Database.Pdp.ToDomainObject()}};
                ctx.Entries.Add(new ConversionContextEntry(typeof(SPWeb), mockWeb));
            }
        }

        [Converter]
        public static SPList ListFromWebAndName(SPWeb web, String name)
        {
            return web.Lists.Single(list => list.Name == name);
        }

        [JsonFactory]
        public static SPListItem ListItemFromJson(SPList list, JsonValue json)
        {
            if (json.ContainsKey("Id"))
            {
                return list.Items.Single(item => item.Fields["Id"] == json["Id"]);
            }
            else
            {
                return new SPListItem(list);
            }
        }

        [JsonPbagProvider]
        public static IJsonPbag ListItemToJsonMapping(SPListItem listItem)
        {
            return JsonPbag.ReadWrite(
                () => listItem.Fields.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.GetType()),
                name => listItem.Fields[name],
                (name, value) => listItem.Fields[name] = value);
        }
    }
}